<template>
  <q-page class="q-pa-md">
    <div class="q-pb-md text-h5"> {{pageTitle}} <span class="text-subtitle1">{{pageSubTitle}}</span></div>
    <div class="q-pa-sm shadow-2 q-mb-md">
      <div class="btn q-gutter-sm">
        <q-btn @click="detailNav.goBackToList" color="primary" icon="arrow_back" outline :title="$t('返回')" no-caps />
        <q-btn :disable="loadingState" :loading="loadingState" @click="loadModelData" color="primary" dense
          icon="refresh" outline :title="$t('刷新')" no-caps v-if="isViewOrEditMode" />
        <q-btn :disable="loadingStateGetRightsTreeOfRole" @click="detailNav.goEditMode()" color="primary" icon="edit"
          :label="$t('编辑')" no-caps
          v-if="isViewMode && !isAdministratorRole && fx.hasModifyRight('Comm.RoleRight.Edit')" />
        <q-btn :disable="loadingStateGetRightsTreeOfRole" @click="deleteRoleRight" color="red" icon="delete_outline"
          :label="$t('删除')" no-caps
          v-if="isViewMode && !isAdministratorRole && fx.hasModifyRight('Comm.RoleRight.Edit')" />
        <q-btn :disable="loadingStateGetRightsTreeOfRole || loadingState" :loading="workingStateSubmit" @click="doSubmit"
          color="primary" :label="$t('确定')" no-caps
          v-if="isCreateOrEditMode" />
        <q-btn :disable="loadingStateGetRightsTreeOfRole" @click="detailNav.cancelSubmit" color="primary" :label="$t('取消')" no-caps
          outline
          v-if="isEditMode" />
      </div>
    </div>
    <!--错误提示-->
    <q-banner class="text-white bg-red q-mt-md" dense inline-actions v-if="serverErrorMessage">
      {{serverErrorMessage}}
      <template v-slot:action>
        <q-btn @click="serverErrorMessage=null" dense flat icon="close" size="sm" />
      </template>
    </q-banner>
    <form-field-group :model-with-create-update="$d.form" class="q-mt-md" model-id="roleId" title="主要信息" no-caps>
      <div class="q-pa-sm q-col-gutter-sm">
        <div class="row q-col-gutter-sm">
          <div class="col-xs-12 col-sm-12 col-md-6 col-lg-3">
            <q-icon color="red" name="fas fa-asterisk" size="10px" />
            <span>{{$t('角色名称')}}</span>
            <q-input :error="v$.roleName.$error" :error-message="e$(v$.roleName.$errors)" :hide-bottom-space="true"
              :readonly="isViewMode" dense :maxlength="30" no-error-icon outlined square stack-label
              v-model="$d.form.roleName" autofocus></q-input>
          </div>
          <div class="col-xs-12 col-sm-12 col-md-12 col-lg-9">
            <span>{{$t('描述')}}</span>
            <q-input :readonly="isViewMode" dense :maxlength="300" outlined square stack-label
              v-model="$d.form.descriptions"></q-input>
          </div>
        </div>
        <div class="row q-col-gutter-sm">
          <div class="col-xs-12 col-sm-12 col-md-12 col-lg-6">
            <span>{{$t('菜单权限')}}</span>
            <div class="full-width q-py-xs">
              <div class="float-right">
                <q-btn @click="expandAllRightTreeNodes" class="q-ml-xs" color="primary" dense outline :title="$t('展开所有')" no-caps>
                  <span class="text-weight-bold" style="width:22px">+</span>
                </q-btn>
                <q-btn @click="expandRightTreeToLevelOne" class="q-ml-xs" color="primary" dense outline :title="$t('展开1级')" no-caps>
                  <span class="text-weight-bold" style="width:22px">Ⅰ</span>
                </q-btn>
                <q-btn @click="collapseAllRightTreeNodes" class="q-ml-xs" color="primary" dense outline :title="$t('折叠所有')" no-caps>
                  <span class="text-weight-bold" style="width:22px">-</span>
                </q-btn>
              </div>
              <q-input clearable dense :maxlength="30" outlined :placeholder="$t('查找/过滤')" square stack-label
                v-model="rightTreeFilter" />
            </div>
            <q-tree :duration="100" v-model:expanded="$d.rightTreeExpandedInfo" :filter="rightTreeFilter"
              :nodes="roleRightTreeNodes" :tick-strategy="isViewMode?'none':'leaf'" v-model:ticked="$d.form.rightKeys"
              class="simple-border" :no-nodes-label="$t('(空)')" node-key="rightkey"
              ref="theRightTree" style="height:375px;overflow:auto">
              <template v-slot:default-header="prop">
                <span class="text-no-wrap">{{prop.node.label}}</span> <span :title="prop.node.description"
                class="text-grey-6 text-no-wrap text-caption"
                v-if="prop.node.description">&nbsp;-&nbsp;{{prop.node.description}}</span>
              </template>
            </q-tree>
          </div>
          <div class="col-xs-12 col-sm-6 col-md-6 col-lg-3"
            v-if="fx.hasRight('Comm.RoleRight.UserRoleAssign') && isViewOrEditMode">
            <span>{{$t('关联用户')}}</span>
            <q-list bordered dense>
              <div class="q-pa-sm row">
                <q-checkbox class="q-py-xs" dense v-if="isEditMode" v-model="roleRelUserCheckAllState" />
                <q-input :class="isEditMode ?  'q-pl-sm' : ''" :style="isEditMode ? 'width: 90%' : 'width: 100%'"
                  clearable dense :maxlength="30" outlined :placeholder="$t('查找/过滤')"
                  square stack-label
                  v-model="userFilter" />
              </div>
              <div style="height:365px;overflow:auto">
                <q-item :key="user.userName" class="q-px-sm" dense v-for="user of relUserList">
                  <div v-if="isViewMode">{{user.userDisp}}</div>
                  <q-checkbox :label="user.userDisp" :val="user.userName" class="q-py-xs" dense
                    v-if="isEditMode" v-model="$d.roleRelUserNames"></q-checkbox>
                </q-item>
              </div>
            </q-list>
          </div>
        </div>
        <div class="row q-col-gutter-sm">
          <div class="col-xs-12 col-sm-6 col-md-6 col-lg-3" v-if="enableRoleMfRelationDataRight && isViewOrEditMode">
            <span>{{$t('数据权限-客商')}}</span>
            <q-list bordered dense>
              <div class="q-pa-sm row">
                <q-checkbox class="q-py-xs" dense v-if="isEditMode" v-model="roleRelMfCheckAllState" />
                <q-input :class="isEditMode ?  'q-pl-sm' : ''" :style="isEditMode ? 'width: 90%' : 'width: 100%'"
                  clearable dense :maxlength="30" outlined :placeholder="$t('查找/过滤')"
                  square stack-label
                  v-model="mfFilter" />
              </div>
              <div style="height:365px;overflow:auto">
                <q-item :key="mf.mfId" class="q-px-sm" dense v-for="mf of mfDataRightList">
                  <div v-if="isViewMode"><span>{{mf.abbrName}}</span><span class="text-grey-6 text-no-wrap text-caption"
                    v-if="mf.extraInfo">&nbsp;-&nbsp;{{mf.extraInfo}}</span></div>
                  <q-checkbox :label="mf.abbrName" :val="mf.mfId" class="q-py-xs" dense v-if="isEditMode"
                    v-model="$d.form.roleRelMfIds"><span class="text-grey-6 text-no-wrap text-caption"
                    v-if="mf.extraInfo">
                        &nbsp;-&nbsp;{{mf.extraInfo}}
                      </span></q-checkbox>
                </q-item>
              </div>
            </q-list>
          </div>
          <div class="col-xs-12 col-sm-6 col-md-6 col-lg-3" v-if="props.enableRoleStorerOrgRelationDataRight && isViewOrEditMode">
            <span>{{$t('数据权限-客商别')}}</span>
            <q-list bordered dense>
              <div class="q-pa-sm row">
                <q-checkbox class="q-py-xs" dense v-if="isEditMode" v-model="roleRelMfOrgCheckAllState" />
                <q-input :class="isEditMode ?  'q-pl-sm' : ''" :style="isEditMode ? 'width: 90%' : 'width: 100%'"
                  clearable dense :maxlength="30" outlined :placeholder="$t('查找/过滤')"
                  square stack-label
                  v-model="mfOrgFilter" />
              </div>
              <div style="height:365px;overflow:auto">
                <q-item :key="mfOrg.mfOrgId" class="q-px-sm" dense v-for="mfOrg of mfOrgDataRightList">
                  <div v-if="isViewMode"><span>{{mfOrg.mfOrgName}}</span></div>
                  <q-checkbox :label="mfOrg.mfOrgName" :val="mfOrg.mfOrgId" class="q-py-xs" dense v-if="isEditMode"
                    v-model="$d.form.roleRelMfOrgIds"></q-checkbox>
                </q-item>
              </div>
            </q-list>
          </div>
          <div class="col-xs-12 col-sm-6 col-md-6 col-lg-3"
            v-if="props.enableRoleCompanyRelationDataRight && isViewOrEditMode">
            <span>{{$t('数据权限-公司')}}</span>
            <q-select :options="$d.companyListFull" :readonly="isViewMode" clearable dense emit-value filled map-options
              multiple option-label="abbrName" option-value="companyId" options-dense :placeholder="$t('选择关联公司')" square
              stack-label transition-hide="none" transition-show="none" v-model="$d.form.roleRelCompanyIds"></q-select>
          </div>
          <div class="col-xs-12 col-sm-12 col-md-12 col-lg-6"
            v-if="props.enableRoleWhRelationDataRight && isViewOrEditMode">
            <span>{{$t('数据权限-仓库')}}</span>
            <q-select :options="$d.whListFull" :readonly="isViewMode" clearable dense emit-value filled map-options
              multiple option-label="whName" option-value="whId" options-dense :placeholder="$t('选择关联仓库')" square
              stack-label transition-hide="none" transition-show="none" v-model="$d.form.roleRelWhIds"></q-select>
          </div>
          <div class="col-xs-12 col-sm-12 col-md-12 col-lg-6"
            v-if="props.enableRoleCbRelationDataRight && isViewOrEditMode">
            <span>{{$t('数据权限-账册')}}</span>
            <q-select :options="$d.cbListFull" :readonly="isViewMode" clearable dense emit-value filled map-options
              multiple option-label="cbNo" option-value="cbId" options-dense :placeholder="$t('选择关联账册')" square
              stack-label transition-hide="none" transition-show="none" v-model="$d.form.roleRelCbIds"></q-select>
          </div>
        </div>
      </div>
    </form-field-group>
  </q-page>
</template>

<script lang="ts">
export default {
  name: 'roleRightStd'
}
</script>

<script lang="ts" setup>
import {computed, reactive, ref, Ref} from 'vue'
import {useDetailHelper} from '../../hooks/detailHelper'
import {Role} from '../../defs/role'
import {SimUserInfo, MfLite, CompanyLite, GetMfLiteListReq, WmWhLite, BfCbLite, MfOrgLite} from '../../helper/dropdownlist.d'
import _ from 'lodash'
import {useTitleHelper} from '../../hooks/titleHelper'
import useVuelidate from '@vuelidate/core'
import {AxiosResponse} from 'axios'
import FormFieldGroup from 'src/lib/components/FormFieldGroup.vue'
import { useI18n } from 'vue-i18n'
const {t} = useI18n()

const pageTitle = t('角色权限')
useTitleHelper(pageTitle)

interface PropsDef {
  // 启用客商关联关系数据权限 - 客户(通常OMS会用)
  enableRoleCustomerRelationDataRight?: boolean
  // 启用客商关联关系数据权限 - 供应商(通常OMS会用)
  enableRoleVendorRelationDataRight?: boolean
  // 启用客商关联关系数据权限 - 货主(通常BFS/WMS会这么用)
  enableRoleStorerRelationDataRight?: boolean
  // 启用公司关联关系数据权限
  enableRoleCompanyRelationDataRight?: boolean
  // 启用WMS仓库关联关系数据权限
  enableRoleWhRelationDataRight?: boolean
  // 启用BFS账册关联关系数据权限
  enableRoleCbRelationDataRight?: boolean
  // 启用客商别关联关系数据权限
  enableRoleStorerOrgRelationDataRight?: boolean
}

let props = withDefaults(defineProps<PropsDef>(), {
  enableRoleCustomerRelationDataRight: false,
  enableRoleVendorRelationDataRight: false,
  enableRoleStorerRelationDataRight: false,
  enableRoleCompanyRelationDataRight: false,
  enableRoleWhRelationDataRight: false,
  enableRoleCbRelationDataRight: false
})

// 新建时候的默认值
const defFormDataForCreate = {
  isEnabled: true
}

let serverErrorMessage = ref('')

let $d = reactive({
  // 表单数据
  form: {} as Role,
  // 角色权限树
  rightTreeDataOfRole: [] as string [],
  // 树展开信息
  rightTreeExpandedInfo: [] as string[],
  // 所有权限树
  rightTreeDataFull: [] as string[],
  // 当前角色所关联的用户(UserName)
  roleRelUserNames: [] as string[],
  // 客商全量数据
  mfListFull: [] as MfLite[],
  // 客商别全量数据
  mfOrgListFull: [] as MfOrgLite[],
  // 用户全量数据
  userListFull: [] as SimUserInfo[],
  // 公司全量数据
  companyListFull: [] as CompanyLite[],
  // 仓库全量数据
  whListFull: [] as WmWhLite[],
  // 账册全量数据
  cbListFull: [] as BfCbLite[]
})

const validators = $f.validators
//主表单验证
const rules = {
  roleName: {
    required: validators.required,
    roleName: validators.username
  }
}

const v$ = useVuelidate(rules, computed(() => $d.form), {$autoDirty: true})

// 数据加载/提交状态
let workingStateSubmit = ref(false)
let loadingStateGetRightsTreeFull = ref(false)
let loadingStateGetRightsTreeOfRole = ref(false)
let loadingStateGetUserList = ref(false)
let loadingStateGetRoleById = ref(false)
// 第一次加载Model数据的标志位(第一次加载的时候自动展开到第一级，后面就不管了)
let firstLoadModelFlag = ref(true)
// 客商列表过滤
let mfFilter = ref('')
// 客商别列表过滤
let mfOrgFilter = ref('')
// 用户列表过滤
let userFilter = ref('')
// 树形列表过滤
let rightTreeFilter = ref(null)

// 加载总的列表数据，总的权限、总的用户、总的公司
const loadTotalListData = function () {
  // 获取权限树(全部)
  loadingStateGetRightsTreeFull.value = true
  $f.axios
    .get<string[]>('/comm/rr/get-all-rights-tree')
    .then((resp) => {
      $d.rightTreeDataFull = resp.data
      expandRightTreeToLevelOne()
    })
    .catch((err) => {
      $f.ui.showNotifyFailed($f.getAxiosErrMsg(err))
    })
    .finally(() => {
      loadingStateGetRightsTreeFull.value = false
    })

  // 获取用户列表
  loadingStateGetUserList.value = true
  $f.lst.getSimUserInfoList(true)
    .then((resp) => {
      $d.userListFull = _.reject(resp, function (o) {
        return o.userName.toLowerCase() == 'admin'
      })
    })
    .catch((err) => {
      $f.ui.showNotifyFailed($f.getAxiosErrMsg(err))
    })
    .finally(() => {
      loadingStateGetUserList.value = false
    })

  // 获取公司列表
  if (props.enableRoleCompanyRelationDataRight) {
    void $f.lst.getCompanySimpleList()
      .then((resp) => {
        $d.companyListFull = resp
      })
  }

  // 获取仓库列表(WMS)
  if (props.enableRoleWhRelationDataRight) {
    void $f.lst.getWmWhSimpleList()
      .then((resp) => {
        $d.whListFull = resp
      })
  }

  // 获取客商别
  if (props.enableRoleStorerOrgRelationDataRight) {
    void $f.lst.getAllMfOrgSimpleList({
      isStorerOrg: true,
      enabledOnly: true,
      isMfOrgTypeRelationAnd: null,
      ignoreDataRight: null
    })
      .then((resp) => {
        $d.mfOrgListFull = resp.mfOrgLiteList
      })
  }

  // 获取账册列表(BFS)
  if (props.enableRoleCbRelationDataRight) {
    void $f.lst.getBfCbSimpleList()
      .then((resp) => {
        $d.cbListFull = resp
      })
  }

  // 有启用客商关联数据权限的话获取相关类型(客户、供应商、货主)的列表
  if (enableRoleMfRelationDataRight.value) {
    let params: GetMfLiteListReq = {
      isMfTypeRelationAnd: false
    }
    if (props.enableRoleCustomerRelationDataRight) {
      params.isCustomer = true
    }
    if (props.enableRoleVendorRelationDataRight) {
      params.isVendor = true
    }
    if (props.enableRoleStorerRelationDataRight) {
      params.isStorer = true
    }
    params.ignoreDataRight = true
    void $f.lst.getMfSimpleList(params)
      .then((resp) => {
        $d.mfListFull = resp.mfLiteList
      })
  }
}

// 根据角色ID获取数据
const loadModelData = function () {
  serverErrorMessage.value = ''
  loadingStateGetRightsTreeOfRole.value = true
  // 获取权限树(某角色)
  $f.axios
    .get<string[]>('/comm/rr/get-all-rights-tree', {params: {roleId: detailInfo.itemId}})
    .then((resp) => {
      $d.rightTreeDataOfRole = resp.data
      if (firstLoadModelFlag.value) {
        firstLoadModelFlag.value = false
        expandRightTreeToLevelOne()
      }
    })
    .catch((err) => {
      $f.ui.showNotifyFailed($f.getAxiosErrMsg(err))
    })
    .finally(() => {
      loadingStateGetRightsTreeOfRole.value = false
    })

  // 获取角色信息
  loadingStateGetRoleById.value = true
  $f.axios
    .get<Role>('/comm/rr/get-role-by-id/' + detailInfo.itemId)
    .then((resp) => {
      $d.roleRelUserNames = _.map(resp.data.relUsers, 'userName')
      $d.form = resp.data
    })
    .catch((err) => {
      $f.ui.showNotifyFailed($f.getAxiosErrMsg(err))
    })
    .finally(() => {
      loadingStateGetRoleById.value = false
    })
}

// 树展开到1级
const expandRightTreeToLevelOne = function () {
  $d.rightTreeExpandedInfo = _.map(roleRightTreeNodes.value, 'rightkey') as string[]
}

let theRightTree: Ref = ref()

// 展开树所有节点
const expandAllRightTreeNodes = function () {
  theRightTree.value.expandAll()
}
// 收起树所有节点
const collapseAllRightTreeNodes = function () {
  theRightTree.value.collapseAll()
}

// 删除
const deleteRoleRight = function () {
  void $f.ui.messageBox({
    caption: t('操作确认'),
    text: t('确定要删除该角色吗'),
    icon: 'Warning',
    buttons: 'OkCancel',
    delayClose: true
  }).then((btn) => {
    if (btn === 'ok') {
      $f.axios
        .post('/comm/rr/delete-role/', [detailInfo.itemId])
        .then(() => {
          $f.ui.closeMsgBox()
          detailNav.goBackToList()
        })
        .catch((err) => {
          void $f.ui.messageBox({
            caption: t('删除失败'),
            text: $f.getAxiosErrMsg(err),
            icon: $f.getAxiosErrIcon(err),
            buttons: 'Close'
          })
        })
    }
  })
}

// 确定
const doSubmit = function () {
  serverErrorMessage.value = ''
  void v$.value
    .$validate()
    .then((valRes) => {
      if (valRes) {
        if (isEditMode.value) {
          let params = {
            roleId: detailInfo.itemId,
            roleName: $d.form.roleName,
            descriptions: $d.form.descriptions,
            rightKeys: $d.form.rightKeys
          }
          workingStateSubmit.value = true
          void $f.axios.post('/comm/rr/update-role', params)
            .then((): Promise<void | AxiosResponse<void>> => {
              if (props.enableRoleCompanyRelationDataRight) {
                let params = {
                  roleId: detailInfo.itemId,
                  companyIds: $d.form.roleRelCompanyIds
                }
                return $f.axios.post('/comm/rr/set-role-companies', params)
              } else {
                return Promise.resolve()
              }
            })
            .then((): Promise<void | AxiosResponse<void>> => {
              if (props.enableRoleWhRelationDataRight) {
                let params = {
                  roleId: detailInfo.itemId,
                  whIds: $d.form.roleRelWhIds
                }
                return $f.axios.post('/comm/rr/set-role-whs', params)
              } else {
                return Promise.resolve()
              }
            })
            .then((): Promise<void | AxiosResponse<void>> => {
              if (props.enableRoleCbRelationDataRight) {
                let params = {
                  roleId: detailInfo.itemId,
                  cbIds: $d.form.roleRelCbIds
                }
                return $f.axios.post('/comm/rr/set-role-cbs', params)
              } else {
                return Promise.resolve()
              }
            })
            .then((): Promise<void | AxiosResponse<void>> => {
              if (enableRoleMfRelationDataRight.value) {
                let params = {
                  roleId: detailInfo.itemId,
                  mfIds: $d.form.roleRelMfIds
                }
                return $f.axios.post('/comm/rr/set-role-mfs', params)
              } else {
                return Promise.resolve()
              }
            })
            .then((): Promise<void | AxiosResponse<void>> => {
              if (props.enableRoleStorerOrgRelationDataRight) {
                let params = {
                  roleId: detailInfo.itemId,
                  mfOrgIds: $d.form.roleRelMfOrgIds
                }
                return $f.axios.post('/comm/rr/set-role-mf-orgs', params)
              } else {
                return Promise.resolve()
              }
            })
            .then((): Promise<void | AxiosResponse<void>> => {
              if ($f.hasRight('Comm.RoleRight.UserRoleAssign')) {
                let params = {
                  roleId: detailInfo.itemId,
                  userNames: $d.roleRelUserNames
                }
                return $f.axios.post('/comm/rr/set-role-user', params)
              } else {
                return Promise.resolve()
              }
            })
            .then(() => {
              detailNav.doneEdit()
            })
            .catch((err) => {
              serverErrorMessage.value = $f.getAxiosErrMsg(err)
            })
            .finally(() => {
              workingStateSubmit.value = false
            })
        } else if (isCreateMode.value) {
          let params = {
            roleName: $d.form.roleName,
            descriptions: $d.form.descriptions,
            rightKeys: $d.form.rightKeys
          }
          workingStateSubmit.value = true
          $f.axios.post('/comm/rr/create-role/', params)
            .then(() => {
              detailNav.goBackToList()
            })
            .catch((err) => {
              serverErrorMessage.value = $f.getAxiosErrMsg(err)
            })
            .finally(() => {
              workingStateSubmit.value = false
            })
        }
      }
    })
}

// region 计算函数
// 是否启用了 客户、供应商、货主 关联数据权限中的一种
const enableRoleMfRelationDataRight = computed(() => {
  return props.enableRoleCustomerRelationDataRight || props.enableRoleVendorRelationDataRight || props.enableRoleStorerRelationDataRight
})

// 是否管理员角色
const isAdministratorRole = computed(() => {
  return detailInfo.itemId == '1'
})

// 菜单权限树的节点(查看和编辑不一样)
const roleRightTreeNodes = computed(() => {
  if (isViewMode.value) {
    return $d.rightTreeDataOfRole
  } else {
    return $d.rightTreeDataFull
  }
})

// 客商数据权限列表(查看和编辑不一样)
const mfDataRightList = computed(() => {
  let lst: MfLite[]
  if (isViewMode.value) {
    lst = _.filter($d.mfListFull, (mf) => {
      return $d.form.roleRelMfIds?.indexOf(mf.mfId) !== -1
    })
  } else {
    lst = $d.mfListFull
  }
  if (mfFilter.value) {
    return _.filter(lst, (mf) => {
      return mf.abbrName.includes(mfFilter.value) || mf.extraInfo?.includes(mfFilter.value)
    })
  } else {
    return lst
  }
})

// 客商别数据权限列表
const mfOrgDataRightList = computed(() => {
  let lst: MfOrgLite[]
  if (isViewMode.value) {
    lst = _.filter($d.mfOrgListFull, (mf) => {
      return $d.form.roleRelMfOrgIds?.indexOf(mf.mfOrgId) !== -1
    })
  } else {
    lst = $d.mfOrgListFull
  }
  if (mfOrgFilter.value) {
    return _.filter(lst, (mfOrg) => {
      return mfOrg.mfOrgName.includes(mfOrgFilter.value)
    })
  } else {
    return lst
  }
})


// 角色关联用户列表(查看和编辑不一样)
const relUserList = computed(() => {
  let lst: SimUserInfo[]
  if (isViewMode.value) {
    lst = $d.form.relUsers
  } else {
    lst = $d.userListFull
  }
  if (userFilter.value) {
    return _.filter(lst, (user) => {
      return user.userDisp.includes(userFilter.value)
    })
  } else {
    return lst
  }
})

// 加载状态
const loadingState = computed(() => {
  return loadingStateGetRightsTreeFull.value || loadingStateGetRightsTreeOfRole.value || loadingStateGetUserList.value || loadingStateGetRoleById.value
})

const roleRelUserCheckAllState = computed({
  get() {
    if ($d.userListFull.length > 0) {
      if ($d.roleRelUserNames.length == $d.userListFull.length) {
        return true
      } else if ($d.roleRelUserNames.length === 0) {
        return false
      }
    }
    return null
  },
  set(val) {
    $d.roleRelUserNames = val == true ? _.map($d.userListFull, 'userName') : []
  }
})

const roleRelMfCheckAllState = computed({
  get() {
    if ($d.mfListFull.length > 0) {
      if ($d.form.roleRelMfOrgIds) {
        if ($d.form.roleRelMfIds.length == $d.mfListFull.length) {
          return true
        } else if ($d.form.roleRelMfIds.length == 0) {
          return false
        }
      }
    }
    return null
  },
  set(val) {
    $d.form.roleRelMfIds = val === true ? _.map($d.mfListFull, 'mfId') : []
  }
})

const roleRelMfOrgCheckAllState = computed({
  get() {
    if ($d.mfOrgListFull.length > 0) {
      if ($d.form.roleRelMfOrgIds) {
        if ($d.form.roleRelMfOrgIds.length == $d.mfOrgListFull.length) {
          return true
        } else if ($d.form.roleRelMfOrgIds.length == 0) {
          return false
        }
      }
    }
    return null
  },
  set(val) {
    $d.form.roleRelMfOrgIds = val === true ? _.map($d.mfOrgListFull, 'mfOrgId') : []
  }
})
// endregion

const {
  detailInfo,
  detailStatus,
  detailNav
} = useDetailHelper('/comm/cfg/roleright',
  $d.form,
  defFormDataForCreate,
  '/comm/cfg/roleright',
  '/comm/cfg/roleright/detail',
  '/comm/cfg/roleright/create',
  '/comm/cfg/roleright/edit',
  loadModelData,
  serverErrorMessage
)

const {
  isViewMode,
  isCreateMode,
  isEditMode,
  isCreateOrEditMode,
  isViewOrEditMode,
  pageSubTitle
} = detailStatus

// region 初始化
loadTotalListData()
const fx = $f
const e$ = $f.getFieldErrStr
if (isCreateMode.value) {
  $d.form.rightKeys = []
}
// endregion

</script>
